<!-- 关卡 -->
<template>
  <div class="app-container">
    <top-column ref="topColumn" @toItem="toItem" />
    <div class="btns">
      <k-button v-if="authorityHandle(234)" class="top-btn" value="添加箱子" @click.native="addBoxDialog" />
      <k-button v-if="authorityHandle(234)" class="top-btn" value="删除箱子" @click.native="deleteBox" />
      <k-button class="top-btn" value="关卡鼓励饰品" @click.native="giveBabySettingDialog" />
      <k-button class="top-btn" value="加赛" @click.native="givePlusBabyDialog" />
      <el-switch
        v-model="itemData.switch"
        class="el_switch_top"
        active-color="#3b425d"
        inactive-color="#E9EBF2"
        active-text="开启"
        inactive-text="关闭"
        :active-value="0"
        :inactive-value="1"
        :disabled="!authorityHandle(234)"
        @change="setSignStatus($event)"
      />
    </div>

    <!--表格相关 -->
    <el-table
      v-show="itemDataInfo.customsPassBoxMsgList"
      ref="dragTable"
      :data="itemDataInfo.customsPassBoxMsgList"
      fit
      border
      row-key="id"
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column min-width="60px" type="selection" align="center" />
      <el-table-column type="index" label="序号" width="60px" align="center" />
      <el-table-column prop="boxName" min-width="100px" label="箱子名称" align="center" show-overflow-tooltip />
      <el-table-column prop="boxPice" min-width="100px" label="箱子价格" align="center" show-overflow-tooltip />
      <el-table-column min-width="150px" label="箱内饰品" align="center">
        <template slot-scope="scope">
          <div class="cell-baby">
            <span class="ellipsis-span" :title="scope.row.goodsNames">{{ scope.row.goodsNames }}</span>
            <span v-show="scope.row.goodsNames" style="color:#3b425d;margin-left:10px" @click="routerToConfig(scope.row, 24)">详情</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column v-if="authorityHandle(234)" prop="boxQuantity" min-width="120px" label="箱子数量" align="center">
        <editable-cell v-model="row.boxQuantity" slot-scope="{ row }" :show-input="row.editMode" @blur="blurInput(row)" @keyup.enter.native="$event.target.blur()">
          <span slot="content">{{ row.boxQuantity }}</span>
        </editable-cell>
      </el-table-column>
      <el-table-column v-if="!authorityHandle(234)" prop="boxQuantity" min-width="100px" label="箱子数量" align="center" show-overflow-tooltip />
      <el-table-column prop="additionTime" min-width="100px" label="添加时间" align="center" show-overflow-tooltip />
      <el-table-column min-width="200px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.boxSwitch"
            :disabled="!authorityHandle(234)"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="0"
            :inactive-value="1"
            @change="boxOnlineState($event, scope)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加箱子 addBox 弹窗 -->
    <k-dialog
      :show-hide.sync="addBoxShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      title="添加箱子"
      :show-foot="false"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBoxDataEvent"
    >
      <div class="dialog-giveBabySetting">
        <div style="padding:20px;margin-left:50px">
          <label>普通箱子：</label>
          <el-select v-model="boxValueModel" multiple style="width: 70%;" filterable placeholder="请选择">
            <el-option v-for="item in resultOpList" :key="item.lineId" :label="item.lineName" :value="item.lineId" @click.native="selectChange(item)" />
          </el-select>
          <div style="margin-top:10px;margin-bottom:200px">
            <el-tag v-for="(item, index) of checkedBoxsList" :key="item.lineId" closable @close="handleBabyTagDelete(index)">{{ item.lineName }}</el-tag>
          </div>
        </div>
      </div>
    </k-dialog>

    <!-- 关卡鼓励饰品 -->
    <k-dialog
      :show-hide.sync="encourageShowHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="对战鼓励饰品"
      class="give-dialog"
      :two-btn="authorityHandle(234)"
      :close-fun="giveBabyCloseDialog"
      @click="saveGiveBabyData"
    >
      <el-form label-width="auto" class="give_div">
        <el-form-item label="饰品名称：">
          <el-select v-model="goodsValueModel" multiple style="width: 100%;" filterable placeholder="请选择" :disabled="!authorityHandle(234)" @change="selectGiveBabyChange">
            <el-option v-for="item in giveGoodsResultList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>

    <!-- 加赛 -->
    <k-dialog
      :show-hide.sync="plusShowHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="加赛"
      class="give-dialog"
      :two-btn="authorityHandle(234)"
      :close-fun="plusCloseDialog"
      @click="savePlusBabyData"
    >
      <el-form label-width="auto" class="give_div">
        <el-form-item label="饰品名称：">
          <el-select v-model="plusValueModel" :disabled="!authorityHandle(234)" multiple style="width: 100%;" filterable placeholder="请选择" @change="plusGiveBabyChange">
            <el-option v-for="item in resultOpList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>

  </div>
</template>

<script>
import topColumn from './components/topColumn.vue'
import EditableCell from '@/components/EditableCell'
import Sortable from 'sortablejs'
import { getGeneralList, getGoodsPlatformList } from '@/api/battel/index'
import { selectById, addBoxMsg, updateBoxMsg, deleteBoxMsg, updateSort, selByCustomsPass, setFalseMatch, setGoodsList, getFalseMatch } from '@/api/levelActivity/index.js'
export default {
  components: { topColumn, EditableCell },
  data() {
    return {
      itemData: {},
      itemDataInfo: {},
      multipleSelection: [],

      // 弹框
      addBoxShow: false,
      resultOpList: [],
      checkedBoxsList: [],
      boxValueModel: [],

      encourageShowHide: false,
      goodsValueModel: [],
      giveGoodsResultList: [],
      checkedGiveBabyList: [],

      plusShowHide: false,
      plusValueModel: [],
      checkedplusBabyList: []
    }
  },

  mounted() {},

  methods: {
    // 加赛
    givePlusBabyDialog() {
      if (!this.itemData.id) {
        this.$message.error('请先选择关卡')
        return
      }
      getGeneralList().then(res => {
        this.resultOpList = res.data
      })
      getFalseMatch({ activityCustomsId: this.itemData.id }).then(res => {
        if (res.data.data) {
          this.plusValueModel = res.data.data
        } else {
          this.plusValueModel = []
        }
        this.plusShowHide = true
      })
    },

    plusGiveBabyChange(value) {
      console.log('value: ', value)
      this.checkedplusBabyList = value
    },

    // 加赛关闭
    plusCloseDialog() {
      this.plusShowHide = false
    },

    // 加赛保存
    savePlusBabyData() {
      Object.assign(this.checkedplusBabyList, this.plusValueModel)
      setFalseMatch({ boxList: this.checkedplusBabyList, activityCustomsId: this.itemData.id }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.plusShowHide = false
        } else {
          this.$message.success(res.data.msg)
        }
      })
    },

    routerToConfig(row, permissionid) {
      this.$router.push({ path: '/rootplayrules/config-babylibnew', query: { id: row.boxId, permissionid }})
    },
    // 子传父 信息
    toItem(v) {
      this.itemData = v
      if (v.id) {
        this.getItemData(v.id)
      } else {
        this.itemDataInfo = {}
      }
    },

    getItemData(id) {
      selectById({ id }).then(res => {
        this.itemDataInfo = res.data.data
        const list = JSON.parse(JSON.stringify(this.itemDataInfo.customsPassBoxMsgList))
        list.map(row => {
          return {
            ...row,
            editMode: false
          }
        })
        this.itemDataInfo.customsPassBoxMsgList = list
        if (this.authorityHandle(234)) {
          this.$nextTick(() => {
            this.setSort()
          })
        }
      })
    },

    blurInput(row) {
      this.modifyItemNote(row)
    },
    // 修改箱子数量
    modifyItemNote(row) {
      const numRegex = /^[1-9]\d*$/
      if (!numRegex.test(row.boxQuantity)) {
        this.$message.error('请输入正整数')
        this.getItemData(this.itemData.id)
        return
      }
      // if (!row.describe) return
      updateBoxMsg({ id: row.id, boxQuantity: row.boxQuantity }).then(res => {
        if (res.data.success) {
          this.$message.success('修改成功')
          this.getItemData(this.itemData.id)
        } else {
          this.$message.error(res.data.msg)
          this.getItemData(this.itemData.id)
        }
      })
    },

    deleteBox() {
      if (!this.itemData.id) {
        this.$message.error('请先选择关卡')
        return
      }
      if (this.multipleSelection.length == 0) {
        this.$message.error('至少选择一项')
        return
      }
      const boxListId = this.multipleSelection.map(item => item.id)
      deleteBoxMsg({ customsPassId: this.itemData.id, boxListId }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.getItemData(this.itemData.id)
        } else {
          this.$message.error(res.data.msg)
          this.getItemData(this.itemData.id)
        }
      })
    },

    setSort() {
      this.$message.success('保存成功')

      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const list = JSON.parse(JSON.stringify(this.itemDataInfo.customsPassBoxMsgList))
          const targetRow = list.splice(evt.oldIndex, 1)[0]
          list.splice(evt.newIndex, 0, targetRow)
          list.map((item, index) => {
            item.boxSort = index
          })
          updateSort(list).then(res => {
            this.getItemData(this.itemData.id)
          })
        }
      })
    },

    // 总开关
    setSignStatus(event) {
      if (!this.itemData.id) {
        this.$message.error('请先选择关卡')
        return
      }
      this.$refs.topColumn.setSwitch(this.itemData.id, event)
    },

    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = val
    },

    // 单个开关
    boxOnlineState(event, scope) {
      const id = scope.row.id
      updateBoxMsg({
        id: id,
        boxSwitch: event
      }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.getItemData(this.itemData.id)
        } else {
          this.$message.error(res.data.msg)
          this.getItemData(this.itemData.id)
        }
      })
    },

    // 添加箱子
    // 开启
    addBoxDialog() {
      if (!this.itemData.id) {
        this.$message.error('请先选择关卡')
        return
      }
      this.checkedBoxsList = []
      getGeneralList().then(res => {
        this.resultOpList = res.data
      })
      this.addBoxShow = true
    },

    // 箱子选择事件
    selectChange(item) {
      const itemIndex = this.checkedBoxsList.findIndex(v => {
        return v.lineId === item.lineId
      })
      if (itemIndex === -1) {
        this.checkedBoxsList.push(item)
      } else {
        this.checkedBoxsList.splice(itemIndex, 1)
      }
    },

    // 删除单项
    handleBabyTagDelete(index) {
      this.checkedBoxsList.splice(index, 1)
      this.boxValueModel.splice(index, 1)
    },

    // 保存
    saveBoxDataEvent() {
      const boxListId = this.checkedBoxsList.map(item => {
        return item.lineId
      })
      addBoxMsg({ boxListId, customsPassId: this.itemData.id }).then(res => {
        if (res.data.success) {
          this.getItemData(this.itemData.id)
          this.$message.success('保存成功')
          this.addBoxShow = false
          this.boxValueModel = []
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    // 关闭
    handleCloseDialog() {
      this.addBoxShow = false
    },

    // 鼓励饰品

    // 开启
    giveBabySettingDialog() {
      if (!this.itemData.id) {
        this.$message.error('请先选择关卡')
        return
      }
      this.getGoodsPlatformList()
      selByCustomsPass({ id: this.itemData.id }).then(res => {
        this.goodsValueModel = res.data.data
      })
      this.encourageShowHide = true
    },

    // 请求赠送全部饰品
    getGoodsPlatformList() {
      getGoodsPlatformList({ key: '', alreadyIds: '[-1]' }).then(res => {
        this.giveGoodsResultList = []
        Object.assign(this.giveGoodsResultList, res.data)
      })
    },

    // 关闭
    selectGiveBabyChange(value) {
      this.checkedGiveBabyList = value
    },

    // 保存赠送饰品配置
    saveGiveBabyData() {
      Object.assign(this.checkedGiveBabyList, this.goodsValueModel)
      setGoodsList({ goodsList: this.checkedGiveBabyList, id: this.itemData.id }).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.encourageShowHide = false
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    // 关闭
    giveBabyCloseDialog() {
      this.encourageShowHide = false
    }
  }
}
</script>

<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.addBox-dialog {
	::v-deep .el-dialog__body {
		width: 678px;
		padding: 10px 30px 30px 30px;
	}
	::v-deep .image-slot {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		background: #f5f7fa;
		color: #909399;
		font-size: 40px;
	}
	::v-deep .el-select .el-select__tags > span {
		display: none;
	}
	.el-tag + .el-tag {
		margin-left: 10px;
	}
	.el-tag {
		color: $mainColor;
		background-color: #ffffff;
		border-color: $mainColor;
		::v-deep .el-tag__close {
			color: $mainColor;
		}
		::v-deep .el-icon-close:hover {
			color: #ffffff;
			background: $mainColor;
		}
	}
}

.give-dialog {
	::v-deep .el-dialog__body {
		width: 678px;
		text-align: center;
	}
	.give_div {
		margin: 0 auto;
		padding: 50px 0px;
		height: 400px;
	}
}
.filter-container {
	width: 100%;
	height: 48px;
	line-height: 48px;

	.filter-item {
		display: inline-block;
		vertical-align: middle;
		margin-bottom: 10px;
	}

	.kInput {
		position: absolute;
		right: 20px;
	}

	.filter-title {
		height: 48px;
		line-height: 48px;
		font-size: 16px;
		font-weight: 500;
		margin-right: 22px;
		color: #14162e;
	}

	.user-item {
		margin-left: 10px;
		margin-right: 20px;
	}

	.room-type,
	.user-status,
	.account-status {
		margin-right: 20px;
	}
}
.btns {
	position: relative;
	height: 50px;
	margin-bottom: 30px;
	.el_switch_top {
		position: absolute;
		right: 50px;
		top: 50%;
		transform: translateY(-50%);
	}
}

.cell-baby {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
}
.ellipsis-span {
	width: 100px;
	overflow: hidden;
	display: inline-block;
	text-overflow: ellipsis;
	white-space: nowrap;
}
</style>
